package ar.com.larreta.reportes;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPdfExporterParameter;

import org.apache.log4j.Logger;

public class PDF extends TipoReporte{

	/** The Constant log. */
	private static final Logger log = Logger.getLogger(TipoReporte.class);
	
	public static final String PDF_CONTENT_TYPE = "application/pdf";

	public PDF(UtilidadesReportes reportsUtils, String path) {
		super(reportsUtils, path);
	}
	
	/**
	 * Obtiene un stream de salida con formato PDF
	 * @param dataSource
	 * @return
	 * @throws IOException 
	 */
	public ByteArrayOutputStream getOutputStream(JRDataSource dataSource) throws IOException{
		JasperPrint print = getPrint(dataSource);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			
			//Necesario para que se imprima automaticamente
			 final StringBuffer js = new StringBuffer();
             js.append("var pp = this.getPrintParams();");
             js.append("pp.interactive = pp.constants.interactionLevel.silent;");
             js.append("this.print(pp);");

             final JRPdfExporter exporter = new JRPdfExporter();
             exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
             exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
             exporter.setParameter(JRPdfExporterParameter.PDF_JAVASCRIPT, js.toString());
             exporter.setParameter(JRPdfExporterParameter.FORCE_LINEBREAK_POLICY, Boolean.TRUE);
             exporter.exportReport();
			
			//JasperExportManager.exportReportToPdfStream(print, baos);
		} catch (JRException e) {
			log.error(e);
		}
		
		return baos;
	}

	@Override
	public String getContentType() {
		return PDF_CONTENT_TYPE;
	}
	
}
